package com.yogurt.nacos.starter;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Objects;

@Configuration
@EnableConfigurationProperties(MyCloudDiscoveryProperties.class)
public class MyCloudDiscoveryAutoConfiguration implements ApplicationRunner {

    private MyCloudDiscoveryProperties properties;
    private Environment environment;

    @Autowired
    public MyCloudDiscoveryAutoConfiguration(MyCloudDiscoveryProperties properties, Environment environment) {
        this.properties = properties;
        this.environment = environment;
    }

    @Bean
    public NamingService namingService() throws NacosException {
        // 根据nacos的地址（serverAddr）获取 NamingService
        return NamingFactory.createNamingService(properties.getServerAddr());
    }


    private String getServiceName() {
        // spring.mycloud.nacos.discovery.serverName没有值，则使用spring.application.name
        String serverName = properties.getServerName();
        if (serverName == null || serverName.isEmpty()) {
            serverName = environment.getProperty("spring.application.name");
        }
        return serverName;
    }


    /**
     * 服务注册到nacos中
     * 需要这个服务的IP、服务的端口、服务的名称
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("服务启动，注册到nacos中,MyCloudDiscoveryAutoConfiguration run...");
        String serviceName = getServiceName();
        NamingService namingService = namingService();
        String ip = environment.getProperty("server.address");
        int port = Integer.parseInt(Objects.requireNonNull(environment.getProperty("server.port")));
        System.out.println("MyCloudDiscoveryAutoConfiguration run...end. " + "serverName = " + serviceName + ", ip = " + ip + ", port = " + port);
        namingService.registerInstance(serviceName, ip, port);
    }
}
